import ApiFetchers from "@/apis/api_fetchers"
import { Repository } from "@/atoms/api_repositories"
import { useCallback, useEffect, useState } from "react"
import { toast } from "react-toastify"

export interface RechargeChannel {
    id?: string
    name?: string
    min_amount?: string
    max_amount?: string
    img?: string
}

type PaymentMethod = string

// 规范化支付方式名称
const normalizePaymentMethod = (name: string): PaymentMethod => {
    const normalized = name.toLowerCase()
    if (normalized === "lazada_exchange") return "Lazada"
    return normalized
}

export default () => {
    const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([])
    const [channels, setChannels] = useState<RechargeChannel[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)

    const { fetch: fetchRechargeChannel } = Repository.useRechargeChannelList()

    const fetchRechargeChannelTyped = useCallback(async (): Promise<RechargeChannel[]> => {
        return (await fetchRechargeChannel()) as RechargeChannel[]
    }, [fetchRechargeChannel])

    useEffect(() => {
        const loadPaymentMethods = async () => {
            setLoading(true)
            setError(null)
            try {
                const response = await ApiFetchers.refGetFinanceChannelList({ mode: "1" })
                if (!response || response.data?.length === 0) {
                    toast.error("No payment methods available")
                    setPaymentMethods([])
                    setChannels([])
                    throw new Error("No valid payment methods found")
                }
                setChannels(response.data || [])
                const methods = response.data?.map((channel) =>
                    normalizePaymentMethod(channel.name!),
                )
                setPaymentMethods(methods || [])
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : String(error)
                setError(errorMessage)
                toast.error(errorMessage)
                setPaymentMethods([])
                setChannels([])
            } finally {
                setLoading(false)
            }
        }

        loadPaymentMethods()
    }, [fetchRechargeChannelTyped])

    return {
        paymentMethods,
        channels,
        loading,
        error,
    }
}
